﻿using iTextSharp.text.pdf.qrcode;
using SuporeSliplampApp.Control;
using SuporeSliplampApp.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;


namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// VideoPlayerWindow.xaml 的交互逻辑
    /// </summary>
    public partial class VideoPlayerWindow : Window
    {
        public static event EventHandler<ScrollControl> cutDelegate;

        public static VideoPlayerWindow VideoInstance { get; private set; }

        private bool isDraggingSlider = false;
        private bool _isPlaying = false;
        private DispatcherTimer timer;

        public VideoPlayerWindow(string videoPath)
        {
            InitializeComponent();

            this.mediaElement.LoadedBehavior = MediaState.Manual;

            mediaElement.Source = new Uri(videoPath);
            mediaElement.MediaOpened += MediaElement_MediaOpened;
            mediaElement.MediaEnded += MediaElement_MediaEnded; // 视频\ue62d结束事件

            // 视频启动时处于暂停状态
            playPauseButton.Content = "\ue62d";
            mediaElement.LoadedBehavior = MediaState.Manual;
            VideoInstance = this;
        }

        private void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            if (mediaElement.NaturalDuration.HasTimeSpan)
            {
                videoSlider.Maximum = mediaElement.NaturalDuration.TimeSpan.TotalSeconds;

                totalTimeText.Text = mediaElement.NaturalDuration.TimeSpan.ToString(@"mm\:ss");

                timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromSeconds(1);
                timer.Tick += Timer_Tick;
                timer.Start();
            }
        }

        //private void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
        //{
        //    _isPlaying = false;
        //    mediaElement.Stop();
        //    playPauseButton.Content = "\ue62d";
        //    mediaElement.Position = TimeSpan.Zero; // 重置视频位置
        //    videoSlider.Value = 0; // 重置Slider位置
        //}


        private async void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            await Task.Run(() =>
            {
                Dispatcher.Invoke(() =>
                {
                    _isPlaying = false;
                    mediaElement.Stop();
                    playPauseButton.Content = "\ue62d";
                    mediaElement.Position = TimeSpan.Zero; // 重置视频位置
                    videoSlider.Value = 0; // 重置Slider位置
                });
            });
        }



        private void Timer_Tick(object sender, EventArgs e)
        {
            if (!isDraggingSlider && mediaElement.NaturalDuration.HasTimeSpan)
            {
                videoSlider.Value = mediaElement.Position.TotalSeconds;
                currentTimeText.Text = mediaElement.Position.ToString(@"mm\:ss");
            }
        }

        //private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        //{
        //    if (isDraggingSlider)
        //    {
        //        this.mediaElement.Position = TimeSpan.FromSeconds(videoSlider.Value);
        //    }
        //}

        private void videoSlider_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            isDraggingSlider = true;
            if (timer != null)
            {
                timer.Stop();
            }
        }

        //private void videoSlider_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        //{
        //    isDraggingSlider = false;
        //    //mediaElement.Pause();
        //    this.mediaElement.Position = TimeSpan.FromSeconds(videoSlider.Value);
        //    //mediaElement.Play();
        //    if (timer != null)
        //    {
        //        timer.Start();
        //    }

        //}


        private async void videoSlider_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            isDraggingSlider = false;
            await Task.Run(() =>
            {
                Dispatcher.Invoke(() =>
                {
                    mediaElement.Position = TimeSpan.FromSeconds(videoSlider.Value);
                    if (timer != null)
                    {
                        timer.Start();
                    }
                });
            });
        }


        private void PlayPause_Click(object sender, RoutedEventArgs e)
        {
            if (_isPlaying)
            {
                mediaElement.Pause();
                playPauseButton.Content = "\ue62d";
                _isPlaying = false;
            }
            else
            {
                mediaElement.Play();
                playPauseButton.Content = "\ue6cf";
                _isPlaying = true;

                if (mediaElement.Position.TotalSeconds > 0)
                {
                    videoSlider.Value = mediaElement.Position.TotalSeconds;
                    currentTimeText.Text = mediaElement.Position.ToString(@"mm\:ss");
                }

                if (timer != null)
                {
                    timer.Start();
                }

            }
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            if (mediaElement != null)
            {
                mediaElement.Stop();
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Cut_Click(object sender, RoutedEventArgs e)
        {
            int width = (int)mediaElement.ActualWidth;
            int height = (int)mediaElement.ActualHeight; 
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmfff") + "cut" + ".bmp";

            RenderTargetBitmap renderBitmap = new RenderTargetBitmap(width, height, 0, 0,  System.Windows.Media.PixelFormats.Pbgra32);
            renderBitmap.Render(mediaElement);
            WriteableBitmap writeableBitmap = new WriteableBitmap(renderBitmap);

            using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
            {
                BitmapEncoder encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(writeableBitmap));
                encoder.Save(fileStream);
            }
            ListControlModel model = new ListControlModel { ImgPath = System.AppDomain.CurrentDomain.BaseDirectory + fileName, Name = fileName };
            ScrollControl scrollControl = new ScrollControl();
            scrollControl.DataContext = model;

            //CameraView targetWindow = Application.Current.Windows.OfType<CameraView>().FirstOrDefault();
            //if (targetWindow != null)
            //{
            //    targetWindow.stackList.Children.Add(scrollControl);
            //}

            cutDelegate?.Invoke(this, scrollControl);


        }

        private async void Fastforward_Click(object sender, RoutedEventArgs e)
        {
            //mediaElement.Position = mediaElement.Position + TimeSpan.FromSeconds(10);
            await Task.Run(() =>
            {
                Dispatcher.Invoke(() =>
                {
                    mediaElement.Pause();
                    mediaElement.Position += TimeSpan.FromSeconds(10);
                    mediaElement.Play();
                });
            });
        }

        private async void Rewind_Click(object sender, RoutedEventArgs e)
        {
            //mediaElement.Position -= TimeSpan.FromSeconds(10);
            await Task.Run(() =>
            {
                Dispatcher.Invoke(() =>
                {
                    mediaElement.Pause();
                    mediaElement.Position -= TimeSpan.FromSeconds(10);
                    mediaElement.Play();
                });
            });
        }



    }
}
